package com.example.auction.adapter;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.*;
import android.widget.*;
import com.example.auction.R;
import com.example.auction.activity.AgainAddItemActivity;
import com.example.auction.activity.ItemDetailsViewActivity;
import com.example.auction.bean.Item;
import com.example.auction.sqlite.Sqlite;
import com.example.auction.util.MyPublishedScrollView;
import com.example.auction.util.MyUtil;
import com.example.auction.util.UserDialog;

import java.util.List;

//性能优化，把频繁fvbi优化
public class PublishedItemListAdapter extends BaseAdapter {


    private List<Item> itemList;
    private final LayoutInflater layoutInflater;
    private Context context;

    private View nowView = null;
    private View preView = null;
    private float downx = 0;
    private float upx = 0;
//    private int pos;

    private Integer user_id;
    private String publishstate;
    private Sqlite sqlite;

    //构造方法
    public PublishedItemListAdapter(Context context, List<Item> itemList, Integer user_id, String published) {
        this.context = context;
        this.itemList = itemList;
        //获取用户id
        this.user_id = user_id;
        //我发布的、有人出价
        this.publishstate = published;

        sqlite = new Sqlite(this.context);

        layoutInflater = LayoutInflater.from(context);
    }


    //返回数据源列表的条数
    @Override
    public int getCount() {
        return itemList.size();
    }

    //返回选中的item子项
    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

    //返回选中的item子项的位置（第几条）
    @Override
    public long getItemId(int position) {
        return position;
    }

    //显示数据的主要方法
    @SuppressLint({"ClickableViewAccessibility", "Range"})
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

//        final String info = itemList.get(position).get("info").toString();

        //viewHolder相当于暂时存储数据的容器，减少数据加载时间
        ViewHolder viewHolder = new ViewHolder();

        //优化版，把频繁fvbi优化
        if (convertView == null) {
            //创建视图控件，绑定item子项的布局文件
            convertView = layoutInflater.inflate(R.layout.list_adapter_published_item2, parent, false);

            //绑定数据布局位置
            //viewHolder相当于暂时存储数据的容器
            viewHolder.viewScrollview = convertView.findViewById(R.id.view_scrollview);
            viewHolder.llLeft = convertView.findViewById(R.id.ll_left);

            //商品状态标签
            viewHolder.tvStateLight = convertView.findViewById(R.id.tv_state_light);

            viewHolder.ivPublishedItemListImg = convertView.findViewById(R.id.iv_published_item_list_img);
            viewHolder.tvPublishedItemListName = convertView.findViewById(R.id.tv_published_item_list_name);
            viewHolder.tvPublishedItemListDes = convertView.findViewById(R.id.tv_published_item_list_des);
            viewHolder.tvPublishedItemListMaxPrice = convertView.findViewById(R.id.tv_published_item_list_max_price);

            viewHolder.llPublishedItemListWinner = convertView.findViewById(R.id.ll_published_item_list_winner);
            viewHolder.tvPublishedItemListWinner = convertView.findViewById(R.id.tv_published_item_list_winner);
            viewHolder.tvPublishedItemListEndtime = convertView.findViewById(R.id.tv_published_item_list_endtime);

            viewHolder.ibtnPublishedAgainItem = convertView.findViewById(R.id.ibtn_publish_again);
            viewHolder.ibtnClose = convertView.findViewById(R.id.ibtn_close);
            viewHolder.ibtnDeletePublishedItem = convertView.findViewById(R.id.ibtn_delete_published_item);

            //获取系统服务，Context.WINDOW_SERVICE在获取窗口服务
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            //获取原宽度
            viewHolder.llLeft.getLayoutParams().width = wm.getDefaultDisplay().getWidth();

            //将fvbi的值都保存
            convertView.setTag(viewHolder);
        } else {
            //取出数据，不用多次fvbi，减少数据加载时间
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final View finalView = convertView;

        //滑动菜单
        viewHolder.viewScrollview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //操作：按下、移动、抬起
                switch (event.getAction()) {
                    //按下
                    case MotionEvent.ACTION_DOWN:
                        //获取按下位置
                        downx = event.getX();
                        break;
                    //移动
                    case MotionEvent.ACTION_MOVE:
                        break;
                    //抬起
                    case MotionEvent.ACTION_UP:
                        //获取抬起位置
                        upx = event.getX();
                        float modify = downx - upx;
                        if (modify == 0) {
                            preView = nowView;
                            nowView = v;
                            autoHide1();
//                            TextView t = v.findViewById(R.id.list_title);
//                            Log.i("Furrain", (String) t.getText());
                            return false;
                        } else {
                            if (nowView == null) {
                                preView = null;
                            } else {
                                preView = nowView;
                            }
                            if (nowView == v) {
                                return false;
                            }
                            nowView = v;
                            autoHide();
                            return false;
                        }
                }
                return false;
            }
        });

        //获取位置对应的对象
        Item item = itemList.get(position);
        Integer item_id = itemList.get(position).getItemId();

        Bitmap imagebm = BitmapFactory.decodeByteArray(item.getImage(), 0, item.getImage().length);
        String winnerName = MyUtil.getUserNameByID(context, item.getWinnerId());

        String state = "";
        Cursor cursor = sqlite.selectItem("item_id", item_id.toString(), "item_id desc");
        if (cursor != null && cursor.moveToFirst()) {
            state = cursor.getString(cursor.getColumnIndex("state"));
        }
        //GONE放if中会按钮显示错乱
        viewHolder.ibtnPublishedAgainItem.setVisibility(View.GONE);
        viewHolder.ibtnClose.setVisibility(View.GONE);
        if (state.equals("审核中")) {
            viewHolder.tvStateLight.setBackgroundResource(R.drawable.bg_yellow_radius50);
            viewHolder.ibtnClose.setVisibility(View.VISIBLE);
        } else if (state.equals("已通过")) {
            viewHolder.tvStateLight.setBackgroundResource(R.drawable.bg_green_radius50);
            viewHolder.ibtnClose.setVisibility(View.VISIBLE);
        } else if (state.equals("不通过")) {
            viewHolder.tvStateLight.setBackgroundResource(R.drawable.bg_red_radius50);
            viewHolder.ibtnPublishedAgainItem.setVisibility(View.VISIBLE);
        } else if (state.equals("已结束")) {
            viewHolder.tvStateLight.setBackgroundResource(R.drawable.bg_gray_radius50);
        }


        if (publishstate.equals("我发布的")) {
            viewHolder.llPublishedItemListWinner.setVisibility(View.INVISIBLE);
        } else if (publishstate.equals("有人出价")) {
            viewHolder.llPublishedItemListWinner.setVisibility(View.VISIBLE);
        }

        viewHolder.ivPublishedItemListImg.setImageBitmap(imagebm);
        viewHolder.tvPublishedItemListName.setText(item.getItemName());
        viewHolder.tvPublishedItemListDes.setText(item.getItemDesc());
        viewHolder.tvPublishedItemListMaxPrice.setText(item.getMaxPrice());
        viewHolder.tvPublishedItemListWinner.setText(winnerName);
        viewHolder.tvPublishedItemListEndtime.setText(item.getEndtime());

        //子项点击监听
        viewHolder.llLeft.setOnClickListener(new MyAdapterListener(position));
        //左滑菜单功能监听
        viewHolder.ibtnClose.setOnClickListener(new leftSlideBtn(position));
        viewHolder.ibtnDeletePublishedItem.setOnClickListener(new leftSlideBtn(position));
        viewHolder.ibtnPublishedAgainItem.setOnClickListener(new leftSlideBtn(position));

        return convertView;
    }

    //优化版，把频繁fvbi优化
    class ViewHolder {
        //保存控件数据，防止多次fvbi
        MyPublishedScrollView viewScrollview;

        LinearLayout llLeft;
        ImageView ivPublishedItemListImg;
        TextView tvPublishedItemListName;
        TextView tvPublishedItemListDes;
        TextView tvPublishedItemListMaxPrice;

        LinearLayout llPublishedItemListWinner;
        TextView tvPublishedItemListWinner;
        TextView tvPublishedItemListEndtime;

        TextView tvStateLight;

        ImageButton ibtnClose;
        ImageButton ibtnPublishedAgainItem;
        ImageButton ibtnDeletePublishedItem;

    }


    //！！！十点搞到了六点，防止item点击错乱的方法
    private class MyAdapterListener implements View.OnClickListener {
        private int position;

        public MyAdapterListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            Integer item_id = itemList.get(position).getItemId();
            Toast.makeText(context, "您选择的是：" + item_id, Toast.LENGTH_SHORT).show();

            //将用户id以及点击的拍卖品名传给拍卖品竞价页
            Intent intent = new Intent();
            intent.putExtra("user_id", user_id);
            intent.putExtra("item_id", item_id.toString());
            //传递从哪个页面跳转过去的信标
            intent.putExtra("from", "publish");
            intent.setClass(context, ItemDetailsViewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        }
    }

    @SuppressLint("Range")
    //左滑菜单
    private class leftSlideBtn implements View.OnClickListener {
        private int position;
        private UserDialog publishDialog;
        private Integer item_id;
        private Integer winner_id;
        private Integer owner_id;
        private Cursor cursor;
        private String state;


        public leftSlideBtn(int position) {
            this.position = position;
            item_id = itemList.get(position).getItemId();
            winner_id = itemList.get(position).getWinnerId();
            owner_id = itemList.get(position).getOwnerId();
            cursor = sqlite.selectItem("item_id", item_id.toString(), "item_id desc");

            if (cursor != null && cursor.moveToFirst()) {
                state = cursor.getString(cursor.getColumnIndex("state"));
            }
        }

        @SuppressLint("NonConstantResourceId")
        @Override
        public void onClick(View v) {

            v.scrollTo(0, 0);
            notifyDataSetChanged();
            autoHide1();

            switch (v.getId()) {
                case R.id.ibtn_publish_again:
                    Toast.makeText(context, "111", Toast.LENGTH_SHORT).show();
                    publishDialog = new UserDialog(context, new publishAgainDialog());
                    publishItemState("publishAgain", state);
                    break;
                case R.id.ibtn_close:
//                    Toast.makeText(context, "点击了结束按钮", Toast.LENGTH_SHORT).show();
                    publishDialog = new UserDialog(context, new closeDialog());
                    publishItemState("close", state);
                    break;
                case R.id.ibtn_delete_published_item:
//                    itemList.remove(pos);
//                    Toast.makeText(context, "点击了删除按钮", Toast.LENGTH_SHORT).show();
                    publishDialog = new UserDialog(context, new deleteDialog());
                    publishItemState("delete", state);
                    break;
            }
        }

        //结束拍卖弹出框标题和内容
        private void publishItemState(String clickFrom, String state) {
            //重新发布
            if (clickFrom.equals("publishAgain")) {
                if (state.equals("不通过")) {
                    publishDialog.setTitle("重新发布").show();
                    publishDialog.setContent("请修改后重新发布").show();
                }
            }
            //结束拍卖
            else if (clickFrom.equals("close")) {
                if (state.equals("已通过")) {
                    publishDialog.setTitle("结束拍卖").show();
                    publishDialog.setContent("确认结束后，会通知当前最高价者进行交易").show();
                } else if (state.equals("审核中")) {
                    publishDialog.setTitle("结束拍卖").show();
                    publishDialog.setContent("物品还在审核中，确认结束吗？").show();
                }
            }
            //删除物品
            else {
                if (state.equals("已通过")) {
                    publishDialog.setTitle("删除物品").show();
                    publishDialog.setContent("物品正在拍卖中，不可删除！").show();
                } else if (state.equals("审核中")) {
                    publishDialog.setTitle("删除物品").show();
                    publishDialog.setContent("物品还在审核中，先去结束吧！").show();
                } else if (state.equals("已结束")) {
                    publishDialog.setTitle("删除物品").show();
                    publishDialog.setContent("删除后不可恢复，确认删除吗？").show();
                } else {
                    //不通过
                    publishDialog.setTitle("删除物品").show();
                    publishDialog.setContent("删除后不可恢复，确认删除吗？").show();
                }
            }
        }

        //重新发布弹出框确认按钮
        private class publishAgainDialog implements UserDialog.OnCloseListener {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (state.equals("不通过")) {
                    Intent intent = new Intent(context, AgainAddItemActivity.class);
                    intent.putExtra("user_id", user_id);
                    intent.putExtra("item_id", item_id);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(intent);
                }
                dialog.dismiss();
            }
        }

        //结束拍卖弹出框确认按钮
        private class closeDialog implements UserDialog.OnCloseListener {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (state.equals("已通过") || state.equals("审核中")) {
                    long i = sqlite.updateItem(item_id, "state", "已结束");
                    long j = sqlite.updateItem(item_id, "endtime", MyUtil.getNowDateString());
                    if (i + j > 1) {
                        //刷新界面
                        notifyDataSetChanged();

                        Toast.makeText(context, "已结束拍卖", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, "操作失败", Toast.LENGTH_SHORT).show();
                    }
                    dialog.dismiss();
                }
                //不通过、已结束
                else if (state.equals("不通过") || state.equals("已结束")) {
                    dialog.dismiss();
                }
            }
        }

        //删除物品弹框确认监听
        private class deleteDialog implements UserDialog.OnCloseListener {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (state.equals("已通过")) {

                } else if (state.equals("审核中")) {

                } else if (state.equals("已结束")) {
                    //获取当前物品竞价表
                    Cursor cursor2 = sqlite.selectBid("item_id", item_id.toString());
                    Integer bid_finish = 0;
                    if (cursor2 != null && cursor2.moveToNext()) {
                        bid_finish = cursor2.getInt(cursor2.getColumnIndex("bid_finish"));
                    }

                    if (user_id.equals(owner_id) && !user_id.equals(winner_id) && bid_finish == 0) {
                        //物品已卖出，且买家还没确认收货
                        Toast.makeText(context, "请联系买家确认收货", Toast.LENGTH_SHORT).show();
                    } else {
                        //物品未卖出，可直接删除（设为发布者不可见owner_visible == 1）
                        long i = sqlite.updateItem(item_id, "owner_visible", String.valueOf(0));
                        if (i > 0) {
                            //移除子项
                            itemList.remove(position);
                            //刷新界面
                            notifyDataSetChanged();
                            Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    //不通过
                    long i = sqlite.deleteItem("item_id", item_id.toString());
                    if (i > 0) {
                        //移除子项
                        itemList.remove(position);

                        //刷新界面
                        notifyDataSetChanged();

                        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                }
                dialog.dismiss();
            }
        }
    }

    //删除之后回到原位
    private void autoHide() {
        if (preView != null) {
            MyPublishedScrollView v = (MyPublishedScrollView) preView;
            v.smoothScrollTo(0, 0);
        }
    }

    private void autoHide1() {
        if (preView != null) {
            MyPublishedScrollView view = (MyPublishedScrollView) preView;
            view.smoothScrollTo(0, 0);
        }
        if (nowView != null) {
            MyPublishedScrollView view = (MyPublishedScrollView) nowView;
            view.smoothScrollTo(0, 0);
        }
    }
}
